<template>
  <view class="">
    <view class="bgf pd-2 dis-f align-center" style="background-color: #fff; display: flex; align-items: center; padding: 20rpx">
      <view class="fl" style="float: left">
        <image
          class="icon-img2 border-radius vam"
          style="width: 120rpx; height: 120rpx; border-radius: 20rpx"
          src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/04/10/xiaoqu1_20250410154558A017.jpg"
        >
        </image>
      </view>
      <view class="fl mgl-2" style="max-width: calc(100% - 140rpx); flex-grow: 1; margin-left: 20rpx">
        <view class="title font-semlbold mgb-1 color01 w100 base-ellipsis font-s16">
          {{ (formData.ebComunityName || "") + (formData.ebComunityLdName || "") + "栋" + (formData.ebComunityDyName || "") + "单元" + (formData.ebComunityLayerName || "") + "层" }}
        </view>
        <!-- <view class="dis-ib color06 mgb-1 base-ellipsis font-s12 w100"
                        >
                        <image
                            style="width: 24rpx; height: 24rpx;"
                            class="base-icon mgr-1 vat"
                            src="@/static/tempIcon/address.png"></image>
                        上海市青浦区嘉松中路6999号 756km上海市青浦区嘉松中路6999号 756km上海市青浦区嘉松中路6999号 756km
                    </view> -->
      </view>
    </view>
    <view class="inner-style">
      <view style="background-color: #fff; padding: 20rpx; border-radius: 10rpx; margin-bottom: 20rpx">
        <view style="font-style: 16px; margin-bottom: 20rpx"> 我的账单 </view>
        <view style="display: flex; margin-bottom: 20px">
          <view class="" style="width: 60rpx"></view>
          <view style="flex-grow: 1"> 时间 </view>
          <view style="flex-grow: 1"> 费用 </view>
          <view style="flex-grow: 1"> 物业费赠送比 </view>
        </view>
        <u-radio-group style="" iconSize="10px" size="40rpx" placement="column" v-model="checked" @change="onChangeRadio">
          <u-radio iconSize="20rpx" size="40rpx" placement="column" :customStyle="{ marginBottom: '15px', padding: '0 10rpx' }" v-for="(item, index) of listsData" :key="index" :name="index">
            <view style="flex-grow: 1">{{ item.title }}</view>
            <view style="flex-grow: 1">{{ item.price }}</view>
            <view style="flex-grow: 1">{{ item.percentage }}</view>
            <!-- <template slot="icon">
              <view style="width: 60rpx">
                <view class="radio-icon"></view>
              </view>
            </template> -->
          </u-radio>
        </u-radio-group>
      </view>
      <view class="bgf pd-2 border-radius mgt-2 filed-row" style="background-color: #fff; padding: 20rpx; border-radius: 10rpx; margin-top: 20rpx">
        <!-- <view class="pr">
                        <van-field
                            label-width="100"
                            v-model="gpWyPaymentAmount"
                            type="digit"
                            label="物业费补贴"
                            @input="(val) => changeNumber(val, 1)" />
                        <view class="pa desc">
                            物业费补贴抵扣
                            <span class="colormark font-semlbold">{{paymentPrice}}</span>元
                        </view>
                    </view> -->
        <u-form labelPosition="left">
          <u-form-item style="color: #646566" label-width="210rpx" label="消费补贴" prop="integral" borderBottom>
            <view style="display: flex; align-items: center; justify-content: space-between">
              <view>{{ integral }}</view>
              <view class="desc pa">
                消费补贴抵扣
                <span style="color: #ff8c00">{{ integralPrice }}</span
                >元
              </view>
            </view>
          </u-form-item>
          <u-form-item @click="handleDateClick" :disabled="isStartTimeFixed" style="color: #646566" label-width="210rpx" label="缴纳开始日期" prop="currentDate" borderBottom>
            <view style="display: flex; align-items: center; justify-content: space-between">
              <view v-if="currentDate">{{ currentDate }}</view>
              <view v-else style="color: #646566">选择开始日期</view>
            </view>
          </u-form-item>
          <u-form-item style="color: #646566" label-width="210rpx" label="缴纳结束日期" prop="currentDate" borderBottom>
            <view style="display: flex; align-items: center; justify-content: space-between">
              <view v-if="currentEndDate">{{ currentEndDate }}</view>
              <view v-else style="color: #646566">结束日期</view>
            </view>
          </u-form-item>
          <u-calendar
            :show="showPicker"
            :mode="mode"
            @confirm="onConfirm"
            @close="showPicker = false"
            :defaultDate="calendar.defaultDate"
            :maxDate="calendar.maxDate"
            :minDate="calendar.minDate"
            :monthNum="calendar.monthNum"
          ></u-calendar>
          <u-form-item style="color: #646566" label-width="210rpx" label="付款金额" prop="payPrice" borderBottom>
            <view style="display: flex; align-items: center; justify-content: space-between">
              <view>{{ payPrice }}</view>
            </view>
          </u-form-item>
          <u-form-item style="color: #646566" label-width="210rpx" label="赠送平台积分" prop="awardPoints" fongt>
            <view style="display: flex; align-items: center; justify-content: space-between">
              <view>{{ awardPoints }}</view>
            </view>
          </u-form-item>
        </u-form>

        <!-- <van-field
          readonly
          clickable
          :value="currentDate"
          :disabled="isStartTimeFixed"
          label-width="100"
          name="datetimePicker"
          label="缴纳开始日期"
          placeholder="选择开始日期"
          @click="handleDateClick"
        />
        <van-field :value="currentEndDate" label-width="100" label="缴纳结束日期" placeholder="结束日期" readonly />
        <van-calendar v-model="showPicker" :show-confirm="true" :min-date="minDate" :max-date="maxDate" @confirm="onConfirm" /> -->
        <!-- <van-field label-width="100" label="付款金额" :value="payPrice" readonly />
        <van-field label-width="100" label="赠送平台积分" :value="awardPoints" readonly /> -->
      </view>

      <view class="w100" style="height: 150rpx"></view>
    </view>
    <view
      style="
        position: fixed;
        bottom: 40rpx;
        left: 0;
        right: 0;
        background-color: #fff;
        padding: 20rpx;
        border-radius: 10rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
      "
    >
      <view style="width: 100%; display: flex; justify-content: space-between; align-items: center">
        <view style="flex-grow: 1; display: flex; align-items: center">
          <view style="font-size: 14px">
            合计<span style="color: #ff8c00"> ￥{{ payPrice }} </span>
          </view>
        </view>
        <view style="width: 320rpx; display: flex; justify-content: center; align-items: center" v-if="seeButton">
          <button
            style="flex-grow: 1; border-radius: 50rpx; height: 80rpx; line-height: 80rpx; background-color: #ff8c00; color: #fff; font-size: 16px; margin-right: 20rpx"
            type="info"
            :loading="loading"
            @click="onSubmit"
          >
            立即支付
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { schemeAndPayment, submitPayment } from "../.././../utils/api/local.js";
import getOrderPay from "../../../utils/api/getOrderPay.js";

export default {
  mixins: [getOrderPay],

  computed: {
    /** 实付金额 */
    payPrice() {
      let price = this.allPrice - this.paymentPrice - this.integralPrice;
      //注意事项 实付的*赠送比例 才是最后需要实际赠送的平台积分
      //this.awardPoints=  Math.round(price*this.currentSelRatio);
      return price.toFixed(2);
      // return 0.01;
    },
  },
  watch: {
    checked: {
      handler(val) {
        this.getPrice(val);
      },
    },
  },
  data() {
    return {
      calendar: {
        minDate: "",
        maxDate: "",
        defaultDate: "",
        monthNum: 36,
      },
      mode: "single",
      userInfo: uni.getStorageSync("userInfo") || {},
      // 新增标识：是否固定开始日期（后端传入时设为true）
      isStartTimeFixed: false,
      /** 缴纳日期 */
      currentDate: "",
      /** 缴纳结束日期 */
      currentEndDate: "",
      showPicker: false,
      /** 账单选择 */
      checked: -1,
      /** 消费补贴 */
      integral: 0.0,
      /** 平台积分 */
      gpWyPaymentAmount: 0,
      /** 当前用户平台积分总额 */
      userPropertyIntegral: 0,
      /** 当前用户消费补贴总额 */
      userIntegral: 0,
      /** 平台积分抵扣比例：多少补贴抵多少钱 */
      wuyeDikouWuyejiaofeiBili: 0,
      /** 消费补贴抵扣比例：多少补贴抵多少钱 */
      xiaofeiDikouWuyejiaofeiBili: 0,
      /** 消费补贴抵扣金额 */
      integralPrice: 0.0,
      /** 平台积分抵扣金额 */
      paymentPrice: 0.0,
      /** 付款金额 */
      // payPrice: 0,
      /** 赠送补贴 */
      awardPoints: 0,
      /** 总金额 */
      allPrice: 0,
      /** 确认支付loading */
      // subLoading: false,
      /** 账单列表 */
      listsData: [],
      formData: {},
      orderType: "lszfxcx",
      /**当前选中**/
      currentSelRatio: 1,
      minDate: new Date(2015, 0, 1),
      maxDate: new Date(2030, 0, 31),
      seeButton: "",
    };
  },
  onLoad(option) {
    this.seeButton = this.$globalData.seeButton;
    this.schemeAndPayment(option.houseId);
    this.chooseTimed();
  },
  methods: {
    chooseTimed() {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      if (month <= 9) {
        month = "0" + month;
      }
      if (day <= 9) {
        day = "0" + day;
      }
      let minyear = year - 2;
      let maxyear = year + 2;
      this.calendar.minDate = minyear + "-" + month + "-" + day;
      this.calendar.maxDate = maxyear + "-" + month + "-" + day;
      this.calendar.defaultDate = year + "-" + month + "-" + day;
    },

    handleDateClick() {
      //   if (!this.currentDate) {
      this.showPicker = true;
      //   }
    },
    /** 切换单选 */
    // 修改单选切换逻辑
    onChangeRadio(val) {
      this.getPrice(val);
      // 保留当前日期，仅更新结束日期
      if (this.currentDate) {
        this.calculateEndDate();
      }
    }, // 新增结束日期计算方法
    // calculateEndDate() {
    //   if (this.currentDate && this.listsData[this.checked]) {
    //     const startDate = new Date(this.currentDate);
    //     const monthsToAdd = this.listsData[this.checked].valueM || 0;

    //     // 处理月末日期边界情况（如1月31日+1个月=2月28日）
    //     const endDate = new Date(startDate);
    //     endDate.setMonth(startDate.getMonth() + monthsToAdd);

    //     // 处理跨年情况
    //     if (endDate.getDate() !== startDate.getDate()) {
    //       endDate.setDate(0); // 自动调整到上月最后一天
    //     }

    //     this.currentEndDate = this.formatDate(endDate);
    //   }
    // },
    calculateEndDate() {
      if (this.currentDate && this.listsData[this.checked]) {
        // 处理iOS日期格式兼容
        const startParts = this.currentDate.split("-");
        const startDate = new Date(parseInt(startParts[0]), parseInt(startParts[1]) - 1, parseInt(startParts[2]));

        const monthsToAdd = this.listsData[this.checked].valueM || 0;
        const endDate = new Date(startDate);

        // 处理月份相加
        endDate.setMonth(startDate.getMonth() + monthsToAdd);

        // 处理月末边界（如1月31日+1个月）
        if (endDate.getDate() !== startDate.getDate()) {
          endDate.setDate(0); // 自动调整到上月最后一天
        }

        this.currentEndDate = this.formatDate(endDate);
      }
    },

    /** 提交订单 */
    onChange(type) {
      this.orderType = type;
    },
    // 修改formatDate方法（处理iOS兼容性）
    formatDate(date) {
      // 确保传入的是Date对象
      if (typeof date === "string") {
        const parts = date.split("-");
        date = new Date(parts[0], parts[1] - 1, parts[2]);
      }
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    },
    // 修改onConfirm方法（确保日期对象正确）
    onConfirm(date) {
      this.showPicker = false;
      // 处理van-calendar返回的日期对象
      const selectedDate = new Date(date);
      this.currentDate = this.formatDate(selectedDate);
      this.isStartTimeFixed = false;
      this.calculateEndDate();
    },
    /** 获取基础数据 */
    schemeAndPayment(houseId) {
      schemeAndPayment({
        userId: uni.getStorageSync("uid"),
        houseId,
      }).then((res) => {
        if (res.data.startTime) {
          this.currentDate = new Date(res.data.startTime).toISOString().split("T")[0];
          this.isStartTimeFixed = true; // 标记为固定日期
          this.calculateEndDate(); // 计算初始结束日期
        }
        /** 单价 */
        let stratafeesUnitprice = res.data.stratafeesUnitprice || 1.23;
        /** 房屋建筑面积 */
        let houseArea = res.data.houseInfo.houseArea || 0;
        /** 单月物业费价格 */
        let monthlyProperty = stratafeesUnitprice * houseArea;
        this.formData = {
          ...res.data.houseInfo,
          ...res.data,
        };
        this.listsData = (res.data.ebComunityPropertyIntegralconfigList || []).map((item, key) => {
          return {
            ...item,
            price: (monthlyProperty * item.valueM).toFixed(2),
            percentage: (item.value * 100).toFixed(2) + "%",
          };
        });
        // res.data.userIntegral = 58;
        //console.log('xiaofeiDikouWuyejiaofeiBili:', res.data.xiaofeiDikouWuyejiaofeiBili);
        //console.log('wuyeDikouWuyejiaofeiBili:', res.data.wuyeDikouWuyejiaofeiBili);
        //console.log('res.data:', JSON.stringify(res.data, null, 2));
        // this.isReturnPoints = res.data.isReturnPoints;
        this.userPropertyIntegral = res.data.userPropertyIntegral || 0;
        this.userIntegral = res.data.userIntegral || 0;
        if (this.userIntegral < 0) {
          this.userIntegral = 0;
        }
        this.wuyeDikouWuyejiaofeiBili = res.data.wuyeDikouWuyejiaofeiBili || 0;
        this.xiaofeiDikouWuyejiaofeiBili = res.data.xiaofeiDikouWuyejiaofeiBili || 0;

        this.getPrice(0);
      });
    },
    /** 获取金额和总补贴 */
    getPrice(val) {
      // 初始需求
      let price = 0;
      let ratio = 0;
      if (this.listsData && this.listsData.length) {
        /** 根据选中单选框找出物业费金额和赠送比例 */
        price = Number(this.listsData[val].price || 0);
        ratio = Number(this.listsData[val].value || 0);
      }
      /** 需缴纳总金额 */
      this.allPrice = price.toFixed(2);
      /** 当前选中 */
      this.currentSelRatio = ratio;
      /** 赠送平台积分 */
      let userIntegral = Number(this.userIntegral || 0);
      /** 改版需求：消费补贴不可输入需全部使用，如果补贴过多，按最大补贴使用，则按最大金额计算 */
      let integralPrice = (userIntegral * this.xiaofeiDikouWuyejiaofeiBili).toFixed(2);
      /** 若用户当前账号补贴可抵扣金额大于需缴纳金额，需消费补贴抵扣金额为需缴纳金额，并计算使用消费补贴 */
      if (Number(this.xiaofeiDikouWuyejiaofeiBili)) {
        if (Number(integralPrice) > Number(this.allPrice)) {
          this.integralPrice = this.allPrice;
          this.integral = (this.allPrice / this.xiaofeiDikouWuyejiaofeiBili).toFixed(2);
        } else {
          this.integral = userIntegral.toFixed(2);
          this.integralPrice = integralPrice;
        }
      }
      //实际赠送的平台积分 是实付金额*赠送比例
      let realPrice = this.allPrice - this.paymentPrice - this.integralPrice;
      this.awardPoints = (realPrice * ratio).toFixed(2);
    },
    /** 补贴输入值改变限制 */
    changeNumber(val, type) {
      return false;
      /** 平台积分设置 */
      if (type === 1) {
        /** 输入平台积分额度大于当前用户最大平台积分额度 */
        if (val > this.userPropertyIntegral) {
          this.gpWyPaymentAmount = this.userPropertyIntegral;
          this.$toast(`当前输入补贴不可大于账户所剩平台积分，当前帐号补贴为${this.userPropertyIntegral}`);
        }
        this.paymentPrice = (val * this.wuyeDikouWuyejiaofeiBili).toFixed(2);
      } else {
        /** 输入消费补贴额度大于当前用户最大消费补贴额度 */
        if (val > this.userIntegral) {
          this.integral = this.userIntegral;
          this.$toast(`当前输入补贴不可大于账户所剩消费补贴，当前帐号补贴为${this.userIntegral}`);
        }
        this.integralPrice = (val * this.xiaofeiDikouWuyejiaofeiBili).toFixed(2);
      }
      //this.awardPoints=999999
      this.awardPoints = Math.round(this.payPrice * this.currentSelRatio);
      //console.log("awardPoints====:"+this.awardPoints)
    },
    onChangeFun() {
      this.pay_close = false;
    },
    onSubmit() {
      if (!this.checked && this.checked !== 0) {
        uni.showToast({
          title: "请选择账单",
          icon: "none",
        });
        return false;
      }
      if (this.payPrice < 0) {
        uni.showToast({
          title: "总金额不能为负，请重新输入补贴配置",
          icon: "none",
        });
        return false;
      }
      if (!this.currentDate || !this.currentEndDate) {
        uni.showToast({
          title: "请选择时间",
          icon: "none",
        });
        return false;
      }
      if (this.orderType === "pay_yue" && Number(this.userInfo.nowMoney || 0) < Number(this.payPrice || 0)) {
        uni.showToast({
          title: "所需金额大于账号余额，请先充值",
          icon: "none",
        });
        return false;
      }
      // if (this.orderType===1) {
      // 	this.$toast('微信支付暂不支持')
      // 	return false
      // }
      // this.pay_close = true;
      this.loading = true;
      let item = this.listsData[this.checked];

      submitPayment({
        comunityIntegral: this.gpWyPaymentAmount,
        comunityIntegralDiscount: this.paymentPrice,
        ebComunityHouseId: this.formData.houseInfo.id,
        ebComunityPropertyId: item.ebComunityPropertyId,
        ebComunityPropertyName: item.ebComunityPropertyName,
        ebSystemConfigId: item.id,
        ebSystemConfigName: item.configName,
        ebSystemConfigType: item.configType,
        ebSystemConfigValue: item.valueM,
        discountType: 3,
        ebUserId: uni.getStorageSync("uid"),
        gainIntegralProperty: this.awardPoints,
        payPrice: this.payPrice,
        payablePrice: this.allPrice,
        useIntegral: this.integral,
        useIntegralDiscount: this.integralPrice,
        /** 缴纳开始时间 */
        payStartTime: this.currentDate,
        payEndTime: this.currentEndDate,
        payType: this.orderType,
        payChannel: "public",
      }).then(async (res) => {
        if (res.code === 200) {
          let page = "";
          this.getOption(
            {
              orderNo: res.data.orderNo,
              tab: 5,
              goPagesSuccess: page,
              goPagesFail: page,
            },
            res,
          );
          // uni.request({
          //   url: "https://www.wantongkonggu.cn/api/frontApph7/order/get/pay/lsReceipt",
          //   method: "GET",
          //   data: { leshuaOrderId: leshua },
          //   success: (resd) => {
          //     uni.request({
          //       url: "https://www.wantongkonggu.cn/api/frontApph7/pay/LsQueryPayResult",
          //       method: "GET",
          //       data: { orderNo: resd.data.data.orderId },
          //       success(ressss) { },
          //     });
          //   },
          //   fail: (err) => {
          //     that.errdata = JSON.stringify(err);
          //   },
          //   complete: (ress) => { },
          // });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.uni-radio-row {
  max-height: 35vh;
  overflow-y: auto;

  ::v-deep .van-radio__label {
    display: flex;
    width: calc(200% - 30px);
    margin-left: 0;
  }
}

.filed-row {
  ::v-deep .van-cell {
    padding: 16rpx 0;
  }

  ::v-deep .van-cell::after {
    left: 0;
    right: 0;
  }

  .desc {
    top: 16rpx;
    right: 0;
    z-index: 4;
    line-height: 48rpx;
  }
}
</style>
